package com.dl.blog.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class BaiduApiServiceImpl {

    private static final String API_URL = "https://api.map.baidu.com/location/ip";
    private static final String AK = "0k7kaTtMbqs41P63MsZyhjLW95GKDZiq";
    private static final String COOR = "bd09ll";

    public JSONObject getLocationByIp(String ip) {
        RestTemplate restTemplate = new RestTemplate();

        // 构建请求URL
        String url = String.format("%s?ip=%s&coor=%s&ak=%s", API_URL, ip, COOR, AK);

        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            if (response.getStatusCode().is2xxSuccessful()) {
                String responseBody = response.getBody();
                if (responseBody == null) {
                    throw new RuntimeException("API response body is null");
                }
                JSONObject jsonObject = JSONObject.parseObject(responseBody);

                // 判断接口是否调用成功（status为0表示成功）
                int status = jsonObject.getIntValue("status");
                if (status != 0) {
                    String message = jsonObject.getString("message");
                    throw new RuntimeException("API Error: " + message);
                }
                // 返回解析后的JSON对象
                return jsonObject;
            } else {
                throw new RuntimeException("HTTP请求失败，状态码：" + response.getStatusCodeValue());
            }
        } catch (Exception e) {
            throw new RuntimeException("获取IP地理位置信息失败: " + e.getMessage(), e);
        }
    }
}
